package net.guoyuchen.web.ctrl;

import net.guoyuchen.Hello;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.ByteBuffer;

@Controller
public class HelloController {

    private static TTransport transport;
    private static TProtocol protocol;
    static{
        transport = new TSocket("localhost", 9000);
        try {
            transport.open();
        } catch (TTransportException e) {
            e.printStackTrace();
        }
        protocol = new TBinaryProtocol(transport);
    }


    @RequestMapping(value = "/hello/{name:.*}", method = RequestMethod.GET)
    @ResponseBody
    public String hello(@PathVariable(value = "name") String name, HttpServletRequest request, HttpServletResponse response) throws TException {

        Hello.Client client = new Hello.Client(protocol);
        return client.sayHello(name);

    }

    @RequestMapping(value = "/pdf", method = RequestMethod.GET)
    public void pdf(HttpServletRequest request, HttpServletResponse response) throws TException, IOException {
        Hello.Client client = new Hello.Client(protocol);
        ByteBuffer bb = client.pdf();
        response.setContentType("application/pdf");
        response.setContentLength(bb.array().length);
        response.getOutputStream().write(bb.array());
    }

}
